from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from .models import ChatMessage
from .serializers import MessageSerializer, MessageListSerializer

class ChatViewSet(viewsets.ViewSet):
    permission_classes = [IsAuthenticated]
    
    def create(self, request):
        """发送消息"""
        serializer = MessageSerializer(data=request.data)
        if not serializer.is_valid():
            return Response({
                'code': 400,
                'message': serializer.errors
            }, status=status.HTTP_400_BAD_REQUEST)
            
        message = serializer.save(user=request.user)
        return Response({
            'code': 200,
            'data': MessageSerializer(message).data,
            'message': 'success'
        })

    @action(detail=False, methods=['get'])
    def history(self, request):
        """获取历史记录"""
        page = int(request.query_params.get('page', 1))
        page_size = int(request.query_params.get('pageSize', 20))
        
        messages = ChatMessage.objects.filter(user=request.user).order_by('-timestamp')
        total = messages.count()
        
        start = (page - 1) * page_size
        end = start + page_size
        messages = messages[start:end]
        
        return Response({
            'code': 200,
            'data': {
                'total': total,
                'list': MessageListSerializer(messages, many=True).data
            },
            'message': 'success'
        })

    @action(detail=False, methods=['delete'])
    def delete_history(self, request):
        """删除历史记录"""
        ChatMessage.objects.filter(user=request.user).delete()
        return Response({
            'code': 200,
            'message': 'success'
        })

    @action(detail=False, methods=['post'])
    def export(self, request):
        """导出历史记录"""
        format = request.data.get('format', 'pdf')
        # 这里实现导出逻辑
        return Response({
            'code': 200,
            'data': {
                'url': 'http://example.com/export/123.pdf'
            },
            'message': 'success'
        }) 